package com.finance.action.android.customer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.vo.Deduction;
import com.finance.action.android.autograph.AutographAction;
import com.finance.action.android.autograph.record.AbstractCredit;
import com.finance.entity.Balance;
import com.finance.entity.BalanceRecord;
import com.finance.entity.Sign;
import com.finance.entity.customer.CallRecordInfo;
import com.finance.entity.customer.JingdongConsumption;
import com.finance.entity.customer.TaobaoConsumption;
import com.finance.entity.customer.Token;
import com.finance.entity.customer.UserInfo;
import com.finance.service.BalanceRecordService;
import com.finance.service.BalanceService;
import com.finance.service.SignService;
import com.finance.service.customer.CallRecordInfoService;
import com.finance.service.customer.JingdongConsumptionService;
import com.finance.service.customer.TaobaoConsumptionService;
import com.finance.service.customer.TokenService;
import com.finance.service.customer.UserInfoService;

@Controller("TokenAction")
public class TokenAction {

	@Resource(name = "TokenService")
	private TokenService tokenService;

	@Resource(name = "UserInfoService")
	private UserInfoService userInfoService;

	@Resource(name = "TaobaoConsumptionService")
	private TaobaoConsumptionService taobaoConsumptionService;

	@Resource(name = "JingdongConsumptionService")
	private JingdongConsumptionService jingdongConsumptionService;

	@Resource(name = "CallRecordInfoService")
	private CallRecordInfoService callRecordInfoService;

	@Resource(name = "SignService")
	private SignService signService;

	@Resource(name = "BalanceService")
	private BalanceService balanceService;

	@Resource(name = "BalanceRecordService")
	private BalanceRecordService balanceRecordService;

	// 测试环境
	public static final String api_url = "https://t.limuzhengxin.cn/api/gateway";
	// 生产环境
	// public static final String api_url =
	// "https://api.limuzhengxin.com/api/gateway";

	public static final String api_version = "1.2.0";

	public static final String api_method = "api.common.getResult";

	@ResponseBody
	// @RequestMapping(value = "callBackurl", method = RequestMethod.POST )
	@RequestMapping("callBackurl")
	public String callBackurl1(@RequestParam("uid") String uid,
			@RequestParam("bizType") String bizType,
			@RequestParam("token") String token,
			@RequestParam("code") String code, @RequestParam("msg") String msg)
			throws UnsupportedEncodingException, IOException, ParseException {
		Token token1 = new Token();
		String success = "";
		UserInfo userInfo = userInfoService.selectByPrimaryKey(uid);
		if (userInfo == null) {
			success = "uid错误，没有当前客户";
			System.out.println("uid错误，没有当前客户" + "。当前uid：" + uid);
			return success;
		}
		if (uid.equals("")) {
			success = "uid为空，失败";
			System.out.println("--------------uid为空！！！---------------");
			return success;
		}
		if (token.equals("")) {
			success = "token为空，失败";
			System.out.println("-------------token为空------------");
			return success;
		}
		token1.setKfUserId(uid);
		token1.setToken(token);
		token1.setBizType(bizType);
		List<BasicNameValuePair> reqParam = new ArrayList<BasicNameValuePair>();
		reqParam.add(new BasicNameValuePair("apiKey", AutographAction.api_key));// API授权
		reqParam.add(new BasicNameValuePair("version", api_version));// 版本号
		reqParam.add(new BasicNameValuePair("method", "api.common.getResult"));//
		reqParam.add(new BasicNameValuePair("token", token));
		reqParam.add(new BasicNameValuePair("bizType", bizType));
		AbstractCredit abstractCredit = new AbstractCredit();
		// reqParam.add(new BasicNameValuePair("sign",
		// abstractCredit.getSign(reqParam)));//请求参数签名
		String sign = abstractCredit.getSign(reqParam);
		token1.setSign(sign);
		token1.setCreaTime(new Date());
		tokenService.insert(token1);

		Map<String, String> map = new HashMap<String, String>();
		map.put("method", "api.common.getResult");
		map.put("apiKey", AutographAction.api_key);
		map.put("version", api_version);
		map.put("sign", sign);
		map.put("token", token);
		map.put("bizType", bizType);

		Sign sign2 = new Sign();

		String text = getPostUrl(map);

		sign2.setJson(text);
		sign2.setUid(uid);
		signService.insert(sign2);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (bizType.equals("taobao")) {
			UserInfo user = userInfoService.selectByPrimaryKey(uid);
			Balance balance = balanceService.selectByPrimaryKey(user
					.getUserId());
			Long moy = balance.getBalanceCount() - Deduction.Taobao;
			if (moy < 0) {
				System.out.println("余额不足拉取淘宝信息失败");
			} else {
				JSONObject json1 = JSONObject.fromObject(text);
				JSONObject aJsonObject = json1.getJSONObject("data");
				JSONArray jsonarr = aJsonObject.getJSONArray("orderDetails");

				for (int i = 0; i < jsonarr.size(); i++) {
					JSONObject or = (JSONObject) jsonarr.get(i);
					TaobaoConsumption taobaoConsumption = new TaobaoConsumption();
					taobaoConsumption.setKfUserId(uid);
					taobaoConsumption.setOrderId(or.getString("orderId"));
					taobaoConsumption.setOrderTime(sdf.parse(or
							.getString("orderTime")));
					taobaoConsumption.setOrderStatus(or
							.getString("orderStatus"));
					JSONArray items = or.getJSONArray("items");
					String s1 = items.toString();
					String s2 = s1.substring(0, s1.length() - 1);
					String s3 = s2.substring(1, s2.length());
					JSONObject jsonObj = JSONObject.fromObject(s3);
					taobaoConsumption.setOrderAmt(jsonObj.getLong("itemPrice"));
					taobaoConsumption.setItems(jsonObj.getString("itemName"));

					taobaoConsumption.setItemQuantity(jsonObj
							.getInt("itemQuantity"));
					taobaoConsumption.setReceivePersonName(or.getJSONObject(
							"logisticsInfo").getString("receivePersonName"));
					taobaoConsumption.setReceivePersonMobile(or.getJSONObject(
							"logisticsInfo").getString("receivePersonMobile"));
					taobaoConsumption.setReceiveAddress(or.getJSONObject(
							"logisticsInfo").getString("receiveAddress"));
					taobaoConsumptionService.insert(taobaoConsumption);
					System.err.println("淘宝信息添加成功" + "次数：" + i);
				}
				balance.setBalanceCount(moy);
				balanceService.updateByPrimaryKeySelective(balance);

				BalanceRecord balanceRecord = new BalanceRecord();
				balanceRecord.setUserId(balance.getUserId());
				balanceRecord.setRdTime(new Date());
				balanceRecord.setRdComment("拉取淘宝信息");
				balanceRecord.setRdType(2);
				balanceRecord.setRdValue(Deduction.Taobao);
				balanceRecordService.insert(balanceRecord);
			}

		}
		if (bizType.equals("jd")) {
			UserInfo user = userInfoService.selectByPrimaryKey(uid);
			Balance balance = balanceService.selectByPrimaryKey(user
					.getUserId());
			Long moy = balance.getBalanceCount() - Deduction.Jingdong;
			if (moy < 0) {
				System.out.println("余额不足拉取京东信息失败");
			} else {
				JSONObject json = JSONObject.fromObject(text);
				JSONObject aJsonObject = json.getJSONObject("data");
				JSONArray jsonarr = aJsonObject.getJSONArray("orderDetail");
				SimpleDateFormat sdf1 = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");

				for (int i = 0; i < jsonarr.size(); i++) {
					JSONObject or = (JSONObject) jsonarr.get(i);
					JingdongConsumption jd = new JingdongConsumption();
					jd.setGoodsName(or.getString("goodsName"));
					jd.setConsigneeAddr(or.getString("consigneeAddr"));
					jd.setOrderDate(sdf1.parse(or.getString("orderDate")));
					jd.setOrderMoney(or.getLong("orderMoney"));
					jd.setConsigneePerson(or.getString("consigneePerson"));
					jd.setTel(or.getString("tel"));
					jd.setOrderStatus(or.getString("orderStatus"));
					jd.setPayType("payType");
					jd.setKfUserId(uid);
					jingdongConsumptionService.insert(jd);
					System.err.println("京东信息添加成功" + "次数：" + i);
				}

				balance.setBalanceCount(moy);
				balanceService.updateByPrimaryKeySelective(balance);

				BalanceRecord balanceRecord = new BalanceRecord();
				balanceRecord.setUserId(balance.getUserId());
				balanceRecord.setRdTime(new Date());
				balanceRecord.setRdComment("拉取京东信息");
				balanceRecord.setRdType(2);
				balanceRecord.setRdValue(Deduction.Jingdong);
				balanceRecordService.insert(balanceRecord);
			}

		}
		if (bizType.equals("mobile")) {
			UserInfo user = userInfoService.selectByPrimaryKey(uid);
			Balance balance = balanceService.selectByPrimaryKey(user
					.getUserId());
			Long moy = balance.getBalanceCount() - Deduction.YunYing;
			if (moy < 0) {
				System.out.println("余额不足拉取运营商信息失败");
			} else {
				JSONObject json = JSONObject.fromObject(text);
				JSONObject aJsonObject = json.getJSONObject("data");
				JSONArray jsonarr = aJsonObject.getJSONArray("callRecordInfo");
				SimpleDateFormat sdf1 = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				for (int i = 0; i < jsonarr.size(); i++) {
					JSONObject ca = (JSONObject) jsonarr.get(i);
					CallRecordInfo caInfo = new CallRecordInfo();
					caInfo.setKfUserId(uid);
					caInfo.setCallAddress(ca.getString("callAddress"));
					caInfo.setCallDateTime(sdf1.parse(ca
							.getString("callDateTime")));
					caInfo.setCallTimeLength(ca.getString("callTimeLength"));
					String typeString = ca.getString("callType");
					if (typeString.equals("主叫")) {
						caInfo.setCallType(1);
					} else {
						caInfo.setCallType(2);
					}
					caInfo.setMobileNo(ca.getString("mobileNo"));
					callRecordInfoService.insert(caInfo);
					System.err.println("运营商信息添加成功" + "次数：" + i);
				}

				balance.setBalanceCount(moy);
				balanceService.updateByPrimaryKeySelective(balance);

				BalanceRecord balanceRecord = new BalanceRecord();
				balanceRecord.setUserId(balance.getUserId());
				balanceRecord.setRdTime(new Date());
				balanceRecord.setRdComment("拉取运营商信息");
				balanceRecord.setRdType(2);
				balanceRecord.setRdValue(Deduction.YunYing);
				balanceRecordService.insert(balanceRecord);
			}

		}
		success = "success";
		return success;
	}

	public String getPostUrl(Map<String, String> map)
			throws UnsupportedEncodingException, IOException {
		// 访问准备
		URL url = new URL("https://api.limuzhengxin.com/api/gateway");
		// post参数
		Map<String, String> params = map;

		// 开始访问
		StringBuilder postData = new StringBuilder();
		for (Map.Entry<String, String> param : params.entrySet()) {
			if (postData.length() != 0)
				postData.append('&');
			postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
			postData.append('=');
			postData.append(URLEncoder.encode(String.valueOf(param.getValue()),
					"UTF-8"));
		}
		byte[] postDataBytes = postData.toString().getBytes("UTF-8");

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length",
				String.valueOf(postDataBytes.length));
		conn.setDoOutput(true);
		conn.getOutputStream().write(postDataBytes);

		Reader in = new BufferedReader(new InputStreamReader(
				conn.getInputStream(), "UTF-8"));

		StringBuilder sb = new StringBuilder();
		for (int c; (c = in.read()) >= 0;)
			sb.append((char) c);
		String response = sb.toString();
		// System.out.println(response);
		return response;
	}
}
